<?php
namespace coreLib\ResponseClass;
use coreLib\ErrorClass\Error;

/**
 * 结果返回处理类
 * @desc 向请求端返回结果数据，并在结果返回时进行相关的缓存处理
 **/

class Response{

	private $routeObj;
	private $cacheObj;

	//构造函数
	function __construct($route,$cache){

		$this->routeObj = $route;
		$this->cacheObj = $cache;

	}

	/*
	 * 返回json数据类型的结果集
	 * @params {$isSuccess} true 成功后的结果，false 失败后的结果
	 * @params {$data}	返回的数据集，如果为NULL，可能为之需要返回一个成功的标志，没有需要返回的结果集
	 * @return 没有返回值
	 */
	function responseData($isSuccess,$data=NULL,$isCacheData=false){

		$newData = $data;

		$interfaceMethod = $this->routeObj->nowRequestInterfaceInfo[1]['method'];

		//判断是成功返回还是失败返回
		if($isSuccess){

			//判断是否存在需要返回的数据内容
			if($newData==NULL){

				//判断返回的结果集是否为数组
				if(gettype($newData) == 'array'){
					$rsData = array("success"=>true,"result"=>array());
				}else{
					$rsData = array("success"=>true);
				}

			}else{

				//判断是否需要对数据进行缓存
				if($this->routeObj->isCache){

					if($interfaceMethod == 'ALL' || $interfaceMethod == 'GET'){
						 $this->cacheObj->createFileCacheData($newData);
					}
					
				}
				
				$rsData = array("success"=>true,"result"=>$newData);
			}


		}else{

			//判断是否有CODE，如果没有CODE说明是业务错误，业务错误给的CODE暂定为88888
			if(!isset($data['code'])){

				//保存消息信息
				$message = $newData;

				//构建新的返回消息
				$newData = array("code"=>"88888","message"=>$message);

			}

			$rsData = array("success"=>false,"result" =>$newData);
		}

		//判断是否需要保存接口运行信息
		if($GLOBALS['settings']['debug']){
	
			if($interfaceMethod == 'ALL' || $interfaceMethod == 'GET') {

				if($isCacheData){
					$GLOBALS['settings']['interfaceInfo']["是否使用缓存结果"] = "是";
				}else{
					$GLOBALS['settings']['interfaceInfo']["是否使用缓存结果"] = "否";
				}

			}

		}


		if($GLOBALS['settings']['debug']){
			 $runTime = getMillisecond() - $GLOBALS['settings']['startTime'];
			 $GLOBALS['settings']['interfaceInfo']["接口运行时间"] = $runTime."毫秒（约".($runTime/1000)."秒)";
		}

		if($GLOBALS['settings']['debug']){
			$included_files = get_included_files();
			$includeInt = 0;
			foreach ($included_files as $filename) {
				$GLOBALS['settings']['interfaceInfo']["文件加载顺序如下"][$includeInt] = $filename;
				$includeInt++;
			}
		}

		//在结果中添加运行信息
		if($GLOBALS['settings']['debug']){
			$rsData['interfaceInfo'] = $GLOBALS['settings']['interfaceInfo'];
		}

		//返回最终结果，JSON_UNESCAPED_SLASHES : Json不要编码Unicode  JSON_UNESCAPED_SLASHES
		$jsonData = json_encode($rsData,JSON_UNESCAPED_UNICODE);

		//判断是否开启数据过滤
		if($GLOBALS['settings']['isDataFilter']){
			
			$filterJsonData = $jsonData;

			foreach($GLOBALS['settings']['dataFilter'] as $k=>$v){
				$filterJsonData = str_replace($k,$v,$filterJsonData);
			}

			$jsonData = $filterJsonData;
			 
		}

		echo $jsonData;

		exit();
	}

}